#!/usr/bin/env python
# -*- coding: utf8 -*-
import mediawiki
from types import *

class Category():
    def __init__(self, site = None):
        if isinstance(site, InstanceType):
            self.site = site
        else:
            self.site = mediawiki.login()
        
        self.countAll = self._countMembers('size')
        self.countPages = self._countMembers('pages')
        self.countSubcats = self._countMembers('subcats')
        
        self.recursiveCountAll = self._recursiveCountMembers('size')
        self.recursiveCountPages = self._recursiveCountMembers('pages')
        self.recursiveCountSubcats = self._recursiveCountMembers('subcats')
    
    def _countMembers(self, type):
        def _countFunc(cat):
            _r = self.site.categoryInfo(cat)
            for (_title, _info) in _r.items():
                yield _info[type]
        return _countFunc
    
    def _recursiveCountMembers(self, type):
        def _recursiveCountFunc(cat, depth = 2):
            _countFunc = self._countMembers(type)
            cats = []
            cats.append(self.members(cat, ns = 14))
            allcat = cats[0]
            for i in range(1, depth):
                cats.append(self.members(cats[i-1]))
                allcat.extend(cats[i])
            result = 0
            for _res in _countFunc(allcat):
                result += _res
            return result
        return _recursiveCountFunc
    
    def members(self, cat, ns = -1, exception = ''):
        result = []
        if isinstance(cat, basestring):
            cat = [cat]
        for _c in cat:
            result.extend(self.site.categoryMembers(_c, ns, exception))
        return result